#include "ShareMemAPI.h"

#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/shm.h> 
#include <errno.h>

namespace ShareMemAPI {

    SMHandle CreateShareMem(SM_KEY key, SM_SIZE size) {
        __ENTER_FUNCTION
        //char keybuf[64];
        //memset(keybuf,0,64);
        //sprintf(keybuf,"./%d",key);

        //key = ftok(keybuf,'w'); 
        SMHandle hd = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666);
        printf("handle = %d ,key = %d ,error: %d \r\n", hd, key, errno);
        return hd;
        __LEAVE_FUNCTION
        return SMHandle(-1);

    }

    SMHandle OpenShareMem(SM_KEY key, SM_SIZE Size) {
        __ENTER_FUNCTION
        //char keybuf[64];
        //memset(keybuf,0,64);
        //sprintf(keybuf,"./%d",key);

        //key = ftok(keybuf,'w'); 
        SMHandle hd = shmget(key, Size, 0);
        printf("handle = %d ,key = %d ,error: %d \r\n", hd, key, errno);
        return hd;
        __LEAVE_FUNCTION
        return SMHandle(-1);
    }

    void* MapShareMem(SMHandle handle) {
        __ENTER_FUNCTION

        return shmat(handle, 0, 0);
        __LEAVE_FUNCTION
        return 0;

    }

    int UnMapShareMem(const void* MemoryPtr) {
        __ENTER_FUNCTION
        return shmdt(MemoryPtr);
        __LEAVE_FUNCTION
        return -1;
    }

    int CloseShareMem(SMHandle handle) {
        __ENTER_FUNCTION
        return shmctl(handle, IPC_RMID, 0);
        __LEAVE_FUNCTION
        return -1;
    }

}